package com.btpj.module_search.ui

import android.content.Context
import android.content.Intent
import android.text.TextUtils
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.btpj.jetpack.base.BaseActivity
import com.btpj.jetpack.utils.KeyboardUtil
import com.btpj.module_search.R
import com.btpj.module_search.databinding.ActivitySearchBinding
import kotlinx.android.synthetic.main.activity_search.*

class SearchActivity : BaseActivity<SearchViewModel, ActivitySearchBinding>() {

    companion object {

        fun newInstance(context: Context): Intent {
            return Intent(context, SearchActivity::class.java)
        }
    }

    override fun getLayoutId() = R.layout.activity_search

    override fun initView() {
        addFragment(HotKeyFragment.newInstance(), "HotKeyFragment")

        tv_cancel.setOnClickListener { finish() }
        et_search.requestFocus()
        et_search.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                if (getInputData() == null) {
                    return@setOnEditorActionListener true
                }

                et_search.clearFocus()
                KeyboardUtil.hideKeyboard(et_search)

                addFragment(
                    SearchResultFragment.newInstance(getInputData()!!),
                    "SearchResultFragment"
                )
                return@setOnEditorActionListener true
            }
            return@setOnEditorActionListener false
        }
    }

    private fun addFragment(fragment: Fragment, tag: String) {
        val beginTransaction = supportFragmentManager.beginTransaction()
        beginTransaction.replace(R.id.fl_container, fragment, tag)
        beginTransaction.commit()
    }

    private fun getInputData(): String? {
        val data = et_search.text.toString().trim()
        if (TextUtils.isEmpty(data)) {
            Toast.makeText(this, "请输入后再查询", Toast.LENGTH_SHORT).show()
            return null
        }
        return data
    }

    fun setHotKeyInputSearch(hotKey: String) {
        et_search.setText(hotKey)
        et_search.clearFocus()
        KeyboardUtil.hideKeyboard(et_search)
        addFragment(
            SearchResultFragment.newInstance(hotKey),
            "SearchResultFragment"
        )
    }
}